from fastapi import APIRouter, Request, Response
from fastapi.responses import JSONResponse as JsonResponse

import fitz
import requests
import urllib3

from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

import os
import uuid

from datetime import datetime

from utils.FileUtil import fetch_file
from configs import config

router = APIRouter(prefix="/arxiv", tags=["论文工具"])


@router.post("/query")
async def query(request: Request):
    data = await request.json()

    # 创建一个不验证SSL证书的session（仅用于解决证书问题）
    session = requests.Session()
    
    # 添加重试策略
    retry_strategy = Retry(
        total=3,
        backoff_factor=1,
        status_forcelist=[429, 500, 502, 503, 504],
    )
    
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    
    # 忽略SSL警告
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    # 发送请求并忽略SSL验证
    url = f"https://export.arxiv.org/api/query?search_query={data['search_query']}&start=0&max_results=10&sortBy=submittedDate&sortOrder=descending"
    response = session.get(url, verify=False)
    
    # 返回XML格式数据
    return Response(content=response.content, media_type="application/xml")


@router.post("/read")
async def read(request: Request):
    data = await request.json()

    localdir = f"{config.setting.statics.path}/upload/{datetime.now().strftime('%Y-%m-%d')}"
    os.makedirs(localdir, exist_ok=True)
    localfile = f"{localdir}/{uuid.uuid4()}.pdf"

    fetch_file(data.get("file"), localfile)

    pdf = fitz.open(localfile)
    text_list = [page.get_text() for page in pdf]
    all_text = '\n\n '.join(text_list)
    pdf.close()

    return JsonResponse(content={"data": {"text": all_text}})
